<template>
  <div id="echartsMap" style="position:relative;">
    <div style="height:100px;width:300px;position:absolute;left:0;top:0;z-index:199;">
      <table>
        <tr>
          <td>
            <el-select v-model="valueP" placeholder="省份" @change="provinceSelected">
              <el-option v-for="item in optionProvince" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </td>
          <td>
            <el-select v-model="valuePark" placeholder="工业园" @change="parkSelected">
              <el-option v-for="item in optionPark" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </td>
        </tr>
      </table>
    </div>
    <table style="height:100%;width:100%;">
      <tr>
      <td style="width:75%;" rowspan="2">
        <div id="echartsChina1">
           <div id="echartsChina"></div>
          </div>
      </td>
      <td>
        <div id="decContent">
            <h2 style="margin-left:10px;">数据全景</h2>
            <ul class="login-info-list" style="margin-left:10px;">
              <li class="login-info-item" v-for="(item,index) in listDec" :key="index">
                {{item}}
              </li>
            </ul>
        </div>
      </td>
        </tr>
        <tr>
          <td>
            <el-tabs v-model="activeName" @tab-click="handleClick">
              <el-tab-pane label="区域流量排名" name="third">
                <div id="echartsRigthTop5"></div>
              </el-tab-pane>
              <el-tab-pane label="实时曲线" name="first" >
                <div id="echartsRigthBottom" @dblclick="testDbClick"></div>
              </el-tab-pane>
              <el-tab-pane label="历史曲线" name="second">
                <div id="echartsRigthTop"></div>
              </el-tab-pane>
            </el-tabs>
            <!-- <div id="echartsRigthBottom"></div> -->
          </td>
          </tr>
    </table>
    <el-dialog id="modelShowInfo" center :visible.sync="dialogFormVisible" @close="closeDialog" append-to-body>
        <div id="modelEcharts" style="width:600px;height:480px;">

        </div>
    </el-dialog>
  </div>
</template>

<script>
import option from '../assets/js/map-option.js'
import echartsRigthTopOption from '../assets/js/echartsRightTop.js'
import echartsRigthBottomOption from '../assets/js/echartsRightBottom.js'
require('echarts/map/js/china')
//require('echarts/map/js/province/anhui')
import {
  fetchList,
  getObj,
} from '@/api/bus/sensor/province';

import{
    getLatestSensorList,
  getSensorDataForPeriodOfTime,
  getTop5StaticData,
  getTop5PointData
} from '@/api/bus/sensor/sensorData'
import{
  getObjByProvinceAndCityId
} from '@/api/bus/sensor/industry'

export default {
  name: 'echartsMap',
  data () {
    return {
        myChart:undefined,
        optionProvince: [],
        optionPark:[],
        valuePark : '',
        valueP    : '',
        activeName: 'third',
        listQuery: {
          page: 1,
          limit: 50
        },
        queryId:{
            provinceId:undefined,
            cityId:undefined
        },
        listDec   : [],
      listComponents:[{name:'安徽',path:'/echartsChina/province/AnHui',components:'views/echartsChina/province/AnHui'},
                      {name:'上海',path:'/echartsChina/province/ShangHai',components:'views/echartsChina/province/ShangHai'},
                      {name:'澳门',path:'/echartsChina/province/AoMen',components:'views/echartsChina/province/AoMen'},
                      {name:'福建',path:'/echartsChina/province/FuJian',components:'views/echartsChina/province/FuJian'},
                      {name:'甘肃',path:'/echartsChina/province/GanSu',components:'views/echartsChina/province/GanSu'},
                      {name:'广东',path:'/echartsChina/province/GuangDong',components:'views/echartsChina/province/GuangDong'},
                      {name:'广西',path:'/echartsChina/province/GuangXi',components:'views/echartsChina/province/GuangXi'},
                      {name:'贵州',path:'/echartsChina/province/GuiZhou',components:'views/echartsChina/province/GuiZhou'},
                      {name:'海南',path:'/echartsChina/province/HaiNan',components:'views/echartsChina/province/HaiNan'},
                      {name:'河北',path:'/echartsChina/province/HeBei',components:'views/echartsChina/province/HeBei'},
                      {name:'黑龙江',path:'/echartsChina/province/HeiLongJiang',components:'views/echartsChina/province/HeiLongJiang'},
                      {name:'河南',path:'/echartsChina/province/HeNan',components:'views/echartsChina/province/HeNan'},
                      {name:'湖北',path:'/echartsChina/province/HuBei',components:'views/echartsChina/province/HuBei'},
                      {name:'湖南',path:'/echartsChina/province/HuNan',components:'views/echartsChina/province/HuNan'},
                      {name:'江苏',path:'/echartsChina/province/JiangSu',components:'views/echartsChina/province/JiangSu'},
                      {name:'江西',path:'/echartsChina/province/JiangXi',components:'views/echartsChina/province/JiangXi'},
                      {name:'吉林',path:'/echartsChina/province/JiLin',components:'views/echartsChina/province/JiLin'},
                      {name:'辽宁',path:'/echartsChina/province/NiaoNing',components:'views/echartsChina/province/NiaoNing'},
                      {name:'内蒙古',path:'/echartsChina/province/NeiMengGu',components:'views/echartsChina/province/NeiMengGu'},
                      {name:'宁夏',path:'/echartsChina/province/NingXia',components:'views/echartsChina/province/NingXia'},
                      {name:'青海',path:'/echartsChina/province/QingHai',components:'views/echartsChina/province/QingHai'},
                      {name:'山东',path:'/echartsChina/province/ShanDong',components:'views/echartsChina/province/ShanDong'},
                      {name:'山西',path:'/echartsChina/province/ShanXi',components:'views/echartsChina/province/ShanXi'},
                      {name:'陕西',path:'/echartsChina/province/ShanXi1',components:'views/echartsChina/province/ShanXi1'},
                      {name:'四川',path:'/echartsChina/province/SiChuan',components:'views/echartsChina/province/SiChuan'},
                      {name:'台湾',path:'/echartsChina/province/TaiWan',components:'views/echartsChina/province/TaiWan'},
                      {name:'香港',path:'/echartsChina/province/XiangGang',components:'views/echartsChina/province/XiangGang'},
                      {name:'新疆',path:'/echartsChina/province/XinJiang',components:'views/echartsChina/province/XinJiang'},
                      {name:'西藏',path:'/echartsChina/province/XiZang',components:'views/echartsChina/province/XiZang'},
                      {name:'云南',path:'/echartsChina/province/YunNan',components:'views/echartsChina/province/YunNan'},
                      {name:'浙江',path:'/echartsChina/province/ZheJiang',components:'views/echartsChina/province/ZheJiang'}],
        valueTemp: Math.random() * 500+500,
        datas    : [],
        provincePointTimeData:[],
        provincePointOneHourData:[],
        provincePointOneDayData:[],
        //charts------------
        myOneHourChart:{},
        myOneDayChart:{},
        chartTop5:{},
        myOneHourModelChart:{},
        //---------------
        iStartIndex:0,
        halfOneHourData:[],
        dialogFormVisible:false, //默认对话框隐藏,
        dataXAxis:[],
        dataYAxis:[],
        dataLegend:[],
        top5DataXAxis:[],
        top5DataYAxis:[],
        dataMax:0,
        series:[],

        dataOneHourXAxis:[],
        dataOneHourYAxis:[],
        dataOneHourLegend:[],
        top5OneHourDataXAxis:[],
        top5OneHourDataYAxis:[],
        dataOneHourMax:0,
        OneHourseries:[],
    }
  },
  mounted(){
      this.drawChinaMap();
      this.setPosition();
  },
  methods: {
          //初始化界面数据
          initForm(){
            this.optionProvince=[];
              //初始化省信息的下拉框
              fetchList(this.listQuery).then(response => {
                  if(response == null || response.data.length<1)
                  {
                    alert('未能获取到相关数据');
                    return;
                  }
                  for (let index = 0; index < response.data.records.length; index++) {
                      var vt = response.data.records[index];
                      
                      if(vt.id==1)
                      {
                        //id==1 的时候，默认是全国，过滤掉
                        continue;
                      }
                      this.optionProvince.push({
                        value :vt.id,
                        label :vt.provinceName
                      })
                  }
              });
              //全国各省时点累计流量
              getLatestSensorList("1","COUNTRY").then(response=>{
                if(response == null || response.data.length<1)
                  {
                    alert('未能获取到相关数据');
                    return;
                  }
                  this.refreshEchartsData(response.data);
                  
              });

              setTimeout(() => {
                this.drawTop5();
              }, 200);

          },

          
          getNowFormatDate(ifOneHour,ifOneDay){
                  var timestamp = Date.parse(new Date());
                  var subOneHour = ifOneHour*1*60*60*1000;
                  var subOneDay = ifOneDay*7*24*60*60*1000;

                  timestamp=timestamp-subOneHour-subOneDay;
                  var unixtimestamp = new Date(parseInt(timestamp));
                  var year = 1900 + unixtimestamp.getYear();
                  var month = "0" + (unixtimestamp.getMonth() + 1);
                  var date = "0" + (unixtimestamp.getDate());
                  var hour = "0" + (unixtimestamp.getHours());
                  var minute = "0" + unixtimestamp.getMinutes();
                  var second = "0" + unixtimestamp.getSeconds();
                  return year + "-" + month.substring(month.length-2, month.length)  + "-" + date.substring(date.length-2, date.length)
                      + " " + hour.substring(hour.length-2, hour.length) + ":"
                      + minute.substring(minute.length-2, minute.length) + ":"
                      + second.substring(second.length-2, second.length);
          },

          refreshLineChartData(responseDatas){
            let that = this;
            this.provincePointOneHourData=[];
            that.top5OneHourDataXAxis=[];
            that.top5OneHourDataYAxis=[];
            that.OneHourseries=[];
            if(responseDatas.length != 0){
               for (let index = 0; index < responseDatas.data.length; index++) {
                var vt = responseDatas.data[index];
                var vname = vt[0].searchId;
                that.dataOneHourLegend.push(vname);
                var dataYAxis=[];
                for(let j=0;j<vt.length;j++){
                  var vtt = vt[j];
                  if(index==0)
                  {
                      that.top5OneHourDataXAxis.push(vtt.timePoint);
                  }
                  
                  dataYAxis.push(vtt.data);
                }
                that.OneHourseries.push({
                  name:vname,
                  type:'line',
                  data : dataYAxis
                })
              }
            }
            
            this.myOneHourChart.setOption({
                legend: {
                    data: that.dataOneHourLegend,
                },
                xAxis:{
                  data:that.top5OneHourDataXAxis,
                },
                dataZoom: [{
                    type: 'slider',
                    xAxisIndex: 0,
                    filterMode: 'empty',
                    start: 90,
                    end: 100
                }, {
                    type: 'inside',
                    xAxisIndex: 0,
                    filterMode: 'empty',
                    start: 0,
                    end: 100
                }],
                series:that.OneHourseries
                })
          },
          //刷新当前时点24小时流量图
          refreshOneDayLineChartData(responseDatas){
            let that = this;
            that.provincePointOneDayData=[];
            that.series=[];
            that.top5DataXAxis=[];
            if(responseDatas.length != 0){
               for (let index = 0; index < responseDatas.data.length; index++) {
                var vt = responseDatas.data[index];
                that.dataLegend.push(vt[0].searchName);
                var dataYAxis =[];
                for(let j=0;j<vt.length;j++){
                  var vtt = vt[j];
                  if(index ==0){
                      that.top5DataXAxis.push(vtt.timePoint.substring(11,16));
                  }
                  
                  dataYAxis.push(vtt.data);
                }
                that.series.push({
                  name:vt[0].searchName,
                  type:'line',
                  data :dataYAxis
                })
              }
            }
            this.myOneDayChart.setOption({
                legend: {
                    data: that.dataLegend,
                },
                xAxis:{
                  data:that.top5DataXAxis,
                },
                dataZoom: [{
                    type: 'slider',
                    xAxisIndex: 0,
                    filterMode: 'empty',
                    start: 90,
                    end: 100
                }, {
                    type: 'inside',
                    xAxisIndex: 0,
                    filterMode: 'empty',
                    start: 0,
                    end: 100
                }],
                series:that.series
                })

          },
          //刷新Echarts的数据
          refreshEchartsData(responseDatas){
              //每次刷新数据的时候，将原始数据清空掉，避免数据有影响
              this.provincePointTimeData = [];
              //先将省的数据，及对应的value取出来
              for (let index = 0; index < responseDatas.length; index++) {
                var vt = responseDatas[index];
                this.provincePointTimeData.push({
                    name : this.getProvinceNameById(vt.provinceId),
                    value : vt.data
                })
              }
            
              this.myChart.setOption({
                series:[{
                  data : this.provincePointTimeData
                }]
              })
          },
          getProvinceNameById(id){
              var val = '';
              for (let index = 0; index < this.optionProvince.length; index++) {
                var  vt = this.optionProvince[index];
                if(vt.value == id)
                {
                  val = vt.label;
                  break;
                }
              }
              return val;
          },
          //省区选择后，触发查询时间，查询该省下的工业园区列表
          provinceSelected(value){
            this.optionPark=[];
            this.queryId.provinceId = value;
            getObjByProvinceAndCityId(this.queryId).then(response =>{
              if(response == null || response.data.length<1)
              {
                alert('未能获取到相关数据');
                return;
              }
              for (let index = 0; index < response.data.length; index++) {
                var vt = response.data[index];
                this.optionPark.push({
                  value:vt.id,
                  label:vt.industryName
                })
              }
            })
          },
          parkSelected(value){
            this.$router.push({
              path:'/bus/industry/detail',
              components:'views/bus/industry/detail',
              query:{
                'industryId':value,
              }
            });
          },
          setPosition(){

          },
          //tab标签页的点击事件
          handleClick(tab, event) {
            if(tab.name == 'first')
            {

              setTimeout(() => {
                   this.drawBottom();
              }, 100);
            }
            else if(tab.name == 'second')
            {
              setTimeout(() => {
                   this.drawTop();
              }, 100);
               
            }
            else if( tab.name == 'third')
            {
              // this.dataXAxis=[];
              // this.dataYAxis=[];
              
              setTimeout(() => {
                this.drawTop5();
              }, 200);
                
            }
          },
          drawTop5(){
            let that       = this;
            that.dataXAxis=[];
            that.dataYAxis=[];
            getTop5PointData("1","COUNTRY").then(response=>{
                if(response == null || response.data.length<1)
                {
                  alert('未能获取到相关数据');
                  return;
                }
                for (let index = 0; index < response.data.length; index++) {
                var vt = response.data[index];
                that.dataXAxis.push(Number(vt.data));
                that.dataYAxis.push(vt.searchName);
                if(that.dataMax < Number(vt.data))
                {
                  that.dataMax = Number(vt.data)*1.2;
                }
                } 
                that.chartTop5 = that.$echarts.init(document.getElementById('echartsRigthTop5'));
                that.chartTop5.setOption({
                    color: ['#3398DB'],
                    title: {
                        text: '全国实时流量排行TOP5',
                        //textStyle: {
                        //    color: '#fff'
                        //}
                    },
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        },
                    },
                    legend: {
                        padding:30,
                    },
                    grid: {
                        left: '4%',
                        right: '4%',
                        bottom: '2%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'value',
                        min: 0,
                        max: that.dataMax,
                        axisLabel: {
                            formatter: '{value}',
                            textStyle: {
                                //color: '#fff',  
                                fontWeight: '80'
                            }
                        }
                    },
                    yAxis: {
                        type: 'category',
                        // data: ['湖北省', '湖南省', '河南省', '安徽省', '浙江省', '山东省', '广东省'],
                        data:that.dataYAxis,
                        axisLabel: {
                            show: true,
                            interval: 0,
                            rotate: 0,
                            margin: 10,
                            inside: false,
                            textStyle: {
                                //color: '#fff',
                                fontWeight: '50'
                            }
                        }
                    },
                    series: [{
                        type: 'bar',
                        label: {
                            normal: {
                                show: true,
                                // formatter: '{c}',
                                formatter: function(v) {
                                    var val = v.data;
                                    if (val == 0) {
                                        return '';
                                    }
                                    return val;
                                },
                                color: '#fff'
                            }
                        },
                        // data: [22, 33, 44, 55, 66, 77, 88]
                        data:that.dataXAxis
                    }]
                });
              });
              
           
           
          },
          drawTop(){
            let that       = this;
            that.myOneDayChart = that.$echarts.init(document.getElementById('echartsRigthTop'));
            that.myOneDayChart.setOption({
                title: {
                    text: '全国日累计流量'
                },
                legend: {
                    data: '',
                    padding:30,
                },
                tooltip: {
                    trigger: 'axis',
                    //formatter: "{b} <br> 合格率: {c}%"
                },
                //解决Y轴显示不全的情况
                grid: {
                    left: 60
                },
                xAxis: {
                    type     : 'category',
                    splitLine: {
                        show: true
                    }
                },
                yAxis: {
                    type       : 'value',
                    boundaryGap: [0, '100%'],
                    splitLine  : {
                        show: false
                    },
                    

                },
                series: [{
                    name     : '累计流量数据',
                    type     : 'line',
                    itemStyle: {
                      normal : {
                        lineStyle:{
                          color: 'red'
                        }
                      }
                    },
                    showSymbol    : false,
                    hoverAnimation: false,
                    data          : []
                }]
             });
             var vt = this.getNowFormatDate(0,0);
             var vtOneDayBefore = this.getNowFormatDate(0,1);

             //全国日流量排行
              getTop5StaticData("1","COUNTRY","DAY",vtOneDayBefore,vt).then(response=>{
                  if(response == null || response.data.length<1)
                  {
                    alert('未能获取到相关数据');
                    return;
                  }
                  if(response.data.length>0)
                  {
                       this.refreshOneDayLineChartData(response);
                  }
                 
              });
             
          },
          drawBottom(){
            let that          = this;
            

            var chartBottom = document.getElementById('echartsRigthBottom');
            chartBottom.style.width = document.body.clientWidth*0.25+"px"
            

            this.myOneHourChart = that.$echarts.init(document.getElementById('echartsRigthBottom'));
            this.myOneHourChart.setOption({
               title: {
                    text: '全国实时累计流量'
                },
                legend:{
                  padding:30,
                },
                tooltip: {
                    trigger  : 'axis',
                    // formatter: function (params) {
                    //   console.log(params);
                    //  return params = params[0].seriesName+ '\n'+params[0].data + '---' +parseInt( params[0].data)
                    // },
                    axisPointer: {
                        animation: false,
                        type     : 'none',
                    },
                    extraCssText: 'width:220px; white-space:pre-wrap'
                },
                //解决Y轴显示不全的情况
                grid: {
                    left: 60
                },
                xAxis: {
                    type     : 'category',
                    splitLine: {
                        show: false
                    }
                },
                yAxis: {
                    type       : 'value',
                    boundaryGap: [0, '100%'],
                    splitLine  : {
                        show: false
                    },
                    

                },
                series: [{
                    name     : '实时流量数据',
                    type     : 'line',
                    itemStyle: {
                      normal : {
                        lineStyle:{
                          color: 'red'
                        }
                      }
                    },
                    showSymbol    : false,
                    hoverAnimation: false,
                    data          : []
                }]
             });

              var vt = this.getNowFormatDate(0,0);
              // var vtOneDayBefore = this.this.getNowFormatDate(0,1);
              var vtOneHourBefore = this.getNowFormatDate(1,0);
              //全国当前时点一小时的流量累计
              // getSensorDataForPeriodOfTime("1","COUNTRY",vtOneHourBefore,vt).then(response=>{
              //     if(response == null || response.data.length<1)
              //     {
              //       alert('未能获取到相关数据');
              //       return;
              //     }
              //     this.refreshLineChartData(response);
              // });
              //全国日流量排行
              getTop5StaticData("1","COUNTRY","REAL",vtOneHourBefore,vt).then(response=>{
                  if(response == null || response.data.length<1)
                  {
                    alert('未能获取到相关数据');
                    return;
                  }
                  if(response.data.length>0)
                  {
                        this.refreshLineChartData(response);
                  }
                 
              });

            //  setInterval(function () {
            //    var dataTemp =that.getHalfOneHourData();
            //    if(that.iStartIndex <=29)
            //    {
            //       that.iStartIndex++;
            //    }else{
            //      that.iStartIndex=0;
            //    }

            //  },1000);
          },
          getHalfOneHourData(){
            let that = this;
            that.halfOneHourData=[];
            for (let index = 0; index < 30; index++) {
              that.halfOneHourData.push(that.provincePointOneHourData[that.iStartIndex+index]);
            }
            that.myOneHourChart.setOption({
               xAxis: {
                    type     : 'category',
                    splitLine: {
                        show: false
                    }
                },
                series:[{
                  name     : '实时流量数据',
                    type     : 'line',
                  data : that.halfOneHourData
                }]
              })
          },
          drawChinaMap() {
            let that    = this;
            this.myChart = that.$echarts.init(document.getElementById('echartsChina'));
        
            this.myChart.setOption(option);
            setTimeout(() => {
                that.drawBottom();
                that.initForm();
               
            }, 100);
            this.myChart.on('click', function (params) {
              var comp = that.getComponentsByName(params.name);
              that.$router.push(comp.path,comp.components);
            });

            this.getProvinceInfo();
          },
          getProvinceInfo(){
            //根据查询全国的描述信息
            getObj('1').then(response => {
              if(response == null || response.data.length<1)
              {
                alert('未能获取到相关数据');
                return;
              }
              this.listDec.push(response.data.provinceType);
            })
          },
          getComponentsByName(name){

            for(var i = 0, cm; cm = this.listComponents[i++];){
                if(cm.name == name)
                {
                  return cm;
                }
            }
          },
          drawModelChart(){
             var chartModel = document.getElementById('modelEcharts'); 
            
            this.myOneHourModelChart = this.$echarts.init(document.getElementById('modelEcharts'));
              this.myOneHourModelChart.setOption({
               title: {
                    text: '全国实时累计流量'
                },
                legend:{
                  padding:30,
                },
                tooltip: {
                    trigger  : 'axis',
                    // formatter: function (params) {
                    //   console.log(params);
                    //  return params = params[0].seriesName+ '\n'+params[0].data + '---' +parseInt( params[0].data)
                    // },
                    axisPointer: {
                        animation: false,
                        type     : 'none',
                    },
                    extraCssText: 'width:220px; white-space:pre-wrap'
                },
                //解决Y轴显示不全的情况
                grid: {
                    left: 60
                },
                xAxis: {
                    type     : 'category',
                    splitLine: {
                        show: false
                    },
                    data:this.top5OneHourDataXAxis,
                },
                yAxis: {
                    type       : 'value',
                    boundaryGap: [0, '100%'],
                    splitLine  : {
                        show: false
                    },
                    

                },
                series:this.OneHourseries
             });
          },
          testDbClick(){
            console.log('in');
            if(this.activeName == 'first')
            {
              this.dialogFormVisible = true;
              this.drawModelChart();
              
            }else if(this.activeName == 'second')
            {

            }
            else if(this.activeName == 'third')
            {

            }
            
            
          },
          closeDialog(){
            this.myOneHourModelChart= null;
          },
        }
        
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  #echartsMap{
      width          : 100%;
      height         : 98%;
      display        : flex;
      align-items    : top;
      justify-content: center;
  }


  #echartsChina{
    width : 100%;
    height: 100%;
    /* display:block; */
    float: left;

  }
  #echartsChina1{
    width        : 98%;
    height       : 100%;
    float        : left;
    border-radius: 5px;
    box-sizing   : border-box;
    background   : #fff;
    overflow     : hidden;
  }
  
  #tdMap{
    width : 75%;
    height: 500px;
  }
  #decContent{
    width        : 100%;
    height       : 230px;
    border-radius: 5px;
    box-sizing   : border-box;
    background   : #fff;
    overflow     : hidden;
  }

  #echartsRigthTop{
    width        : 90%;
    height       : 240px;
    border-radius: 5px;
    box-sizing   : border-box;
    background   : #fff;
    overflow     : hidden;
  }

    #echartsRigthTop5{
    width        : 90%;
    height       : 240px;
    border-radius: 5px;
    box-sizing   : border-box;
    background   : #fff;
    overflow     : hidden;
  }

  #echartsRigthBottom{
    margin-top   : 10px;
    width        : 100%;
    height       : 240px;
    border-radius: 5px;
    box-sizing   : border-box;
    background   : #fff;
    overflow     : hidden;
      
  }

</style>
